package com.xjd.edu.user.config;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceWrapper;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
@Configuration
//@EnableUserDataSource
// 扫描主数据源对应的Mapper接口所在包，指定sqlSessionFactory的引用名称
@MapperScan(basePackages = "com.xjd.edu.user.dao.user", sqlSessionFactoryRef = "userSqlSessionFactory")
public class UserDataSourceConfig {

    @Bean(name = "sampleUserDataSource", initMethod = "init")
    @ConfigurationProperties(prefix = "spring.datasource.druid.user")
    public DruidDataSourceWrapper sampleUserDataSource() {
        return new DruidDataSourceWrapper();
    }

    // 配置主数据源对应的SqlSessionFactory
    @Bean(name = "userSqlSessionFactory")
    public SqlSessionFactory userSqlSessionFactory(@Qualifier("sampleUserDataSource") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        // 可以添加更多MyBatis-Plus相关配置，比如配置Mapper文件路径等
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:/mapper/user/*.xml"));
        return bean.getObject();
    }

    // 配置主数据源对应的事务管理器
    @Bean(name = "userTransactionManager")
    public DataSourceTransactionManager userTransactionManager(@Qualifier("sampleUserDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    // 配置主数据源对应的SqlSessionTemplate
    @Bean(name = "userSqlSessionTemplate")
    public SqlSessionTemplate userSqlSessionTemplate(@Qualifier("userSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}